//
//  ICPubMenuView.m
//  ICome
//
//  Created by zhangrongwu on 2016/11/22.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICPubMenuView.h"
#import "NSMutableAttributedString+Extension.h"
#import "ICHeaderFile.h"

#define KeyboardWidth 49.5
#define PubMenuWidth (App_Frame_Width - KeyboardWidth)
#define BTN_TAG_BASE_NUM 5678
#define DEFAULT_COLOR [UIColor colorWithRed:250.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0]
#define DEFAULT_BG_COLOR [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:1.0]

#define FOOTERVIEWH 5
static CGFloat const CellHeight = 40;

@interface ICPubMenuView()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong)UIButton *showKeyboardBtn;
@property (nonatomic, assign)NSUInteger selectedBottomIndex;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)UIImageView *bgImageView;
@property (nonatomic, strong)UIView *displayView;
//滑出菜单是否隐藏
@property (nonatomic, assign)BOOL tableViewHidden;
@property (nonatomic, strong)NSArray *subItems;



@end

@implementation ICPubMenuView

-(instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.displayView.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (instancetype)initWithDisplayView:(UIView *)displayView {
    if (self = [super init]) {
        self.selectedBottomIndex = -1;
        self.displayView = displayView;
    }
    return self;
}

-(void)setBottomItems:(NSMutableArray<ICPubItemModel *> *)bottomItems {
    _bottomItems = bottomItems;
    if (bottomItems.count > 0) {
        self.backgroundColor = [UIColor lightGrayColor];
    } else {
        self.backgroundColor = MENU_BACKGROUND_COLOR;
    }
    //移除
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    
    [self addSubview:self.showKeyboardBtn];
    //添加
    CGFloat btnwidth = (PubMenuWidth - (bottomItems.count-1)*0.5)/bottomItems.count;
    NSString *imageName = @"icon_pub_menu";
    for (int i = 0; i < bottomItems.count; i++) {
        ICPubItemModel *model = bottomItems[i];
        if ([model.type isEqualToString:@"submenu"]) {
            imageName = @"icon_pub_menu";
        } else {
            imageName = @"";
        }
        UIButton *btn = [self btnWithTitle:model.name leftImageName:imageName];
        btn.frame = CGRectMake(KeyboardWidth + (btnwidth + 0.5) * i, 0.5, btnwidth, [ICTools getChatBoxInputHeight] - 0.5 - [ICTools getHomebarHeight]);// CGRectGetHeight(self.frame)-0.5
        btn.tag = BTN_TAG_BASE_NUM + i;
        [self addSubview:btn];
    }
    UIView *homeBarView = [[UIView alloc] initWithFrame:CGRectMake(0, [ICTools getChatBoxInputHeight] - [ICTools getHomebarHeight]+0.5, self.width, [ICTools getHomebarHeight])];
    homeBarView.backgroundColor = MENU_BACKGROUND_COLOR;
    [self addSubview:homeBarView];
}

- (UIButton *)btnWithTitle:(NSString *)title leftImageName:(NSString *)imageName {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [btn setTintAdjustmentMode:UIViewTintAdjustmentModeAutomatic];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn.backgroundColor = MENU_BACKGROUND_COLOR;
    
    
    if (![ICTools stringEmpty:imageName]) {
        NSTextAttachment *attachment = [NSTextAttachment new];
        attachment.image = [UIImage imageNamedFromiComeSDKBundle:imageName];
        attachment.bounds = CGRectMake(0, 0, 10, 10);
        NSAttributedString *atTitle = [NSAttributedString attributedStringWithAttachment:attachment];
        NSMutableAttributedString *titleAttributedString = [[NSMutableAttributedString alloc] init];
        [titleAttributedString appendString:title];
        [titleAttributedString setColor:[UIColor darkGrayColor]];
        [titleAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
        [titleAttributedString appendAttributedString:atTitle];
        
        [btn setAttributedTitle:titleAttributedString forState:UIControlStateNormal];
    } else {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    //    [btn setTitle:[titleAttributedString string] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnHandler:) forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}


- (void)btnHandler:(UIButton *)sender {
    
    NSInteger index = sender.tag - BTN_TAG_BASE_NUM;
    ICPubItemModel *model = self.bottomItems[index];
    if ([model.type isEqualToString:@"submenu"]) { // 打开二级菜单
        if (self.selectedBottomIndex == index) {
            self.tableViewHidden = !self.tableViewHidden;
        } else {
            self.subItems = model.submenu;
            [self showItemTableAtIndex:index];
            [self.tableView reloadData];
        }
    } else { // 进入界面
        [self hiddenItemTable];
        if ([self.delegate respondsToSelector:@selector(clickItemURL:)]) {
            [self.delegate clickItemURL:model.url];
        }
    }
}

- (void)hidePubMenu:(UIButton *)sender { // 隐藏(显示键盘)
    [self hiddenItemTable];
    
    CGRect mframe = self.frame;
    mframe.origin.y = self.displayView.size.height;
    
    [UIView animateWithDuration:0.2 animations:^{
        self.frame = mframe;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)showPubMenu {
    CGRect mframe = self.frame;
    mframe.origin.y = self.displayView.size.height - [ICTools getChatBoxInputHeight];
    [UIView animateWithDuration:0.2 animations:^{
        self.frame = mframe;
    } completion:^(BOOL finished) {
        
    }];
}

-(void)setTableViewHidden:(BOOL)tableViewHidden {
    tableViewHidden ? [self hiddenItemTable] :  [self showItemTableAtIndex:self.selectedBottomIndex];
}

//打开
- (void)showItemTableAtIndex:(NSInteger)index {
    
    CGFloat tableWidth = (PubMenuWidth - (self.bottomItems.count+1))/self.bottomItems.count;// self.segmentedControl.frame.size.width/self.menuItems.count;
    CGRect tableFrame = CGRectMake(KeyboardWidth + tableWidth * index + index + 1, self.displayView.frame.size.height/* - self.frame.size.height*/, tableWidth, CellHeight * self.subItems.count + FOOTERVIEWH);
    
    self.tableView.frame = tableFrame;
    
    
    tableFrame.origin.y = self.displayView.frame.size.height - self.frame.size.height - CellHeight * self.subItems.count - 70 + 64 - FOOTERVIEWH/*(displayViewTable.contentOffset.y + 64)*/;
    [UIView animateWithDuration:0.1 animations:^{
        self.tableView.frame = tableFrame;
        [self setbgImageViewFrame:tableFrame];
    } completion:^(BOOL finished) {
        self.selectedBottomIndex = index;
        _tableViewHidden = NO;
    }];
    
}

//隐藏
- (void)hiddenItemTable {
    
    CGRect tableFrame = self.tableView.frame;
    tableFrame.origin.y = self.displayView.frame.size.height;// - self.frame.size.height;
    [UIView animateWithDuration:0.1 animations:^{
        self.tableView.frame = tableFrame;
        [self setbgImageViewFrame:tableFrame];
    } completion:^(BOOL finished) {
        _tableViewHidden = YES;
    }];
}


- (void)setbgImageViewFrame:(CGRect)frame {
    //    self.bgImageView.image = [self makeImageWithSize:CGSizeMake(frame.size.width, frame.size.height) image:[UIImage imageWithColor:MENU_BACKGROUND_COLOR]];
    self.bgImageView.image = [UIImage imageNamedFromiComeSDKBundle:@"icon_table_bg"];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.subItems.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"ICPubMenuViewTabelViewCell";
    ICPubMenuViewTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[ICPubMenuViewTabelViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    ICPubSubItemModel *model =  [self.subItems objectAtIndex:indexPath.row];
    cell.titleLabel.text = model.name;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self hiddenItemTable];
    if ([self.delegate respondsToSelector:@selector(selectedUpMenuItemAtIndex:bottomIndex:)]) {
        [self.delegate selectedUpMenuItemAtIndex:indexPath.row bottomIndex:self.selectedBottomIndex];
    }
    if ([self.delegate respondsToSelector:@selector(clickItemURL:)]) {
        ICPubSubItemModel *model =  [self.subItems objectAtIndex:indexPath.row];
        [self.delegate clickItemURL:model.url];
    }
}



-(UIButton *)showKeyboardBtn {
    if (!_showKeyboardBtn) {
        _showKeyboardBtn = [[UIButton alloc] init];
        _showKeyboardBtn.frame = CGRectMake(0, 0.5, KeyboardWidth-0.5,[ICTools getChatBoxInputHeight] - 0.5 - [ICTools getHomebarHeight]);// CGRectGetHeight(self.frame)-0.5
        _showKeyboardBtn.backgroundColor = MENU_BACKGROUND_COLOR;
        [_showKeyboardBtn setImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_keyboard_show"] forState:UIControlStateNormal];
        [_showKeyboardBtn addTarget:self action:@selector(hidePubMenu:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _showKeyboardBtn;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]init];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        
        _tableView.layer.cornerRadius = 6;
        _tableView.layer.borderWidth = 0.5;
        _tableView.layer.borderColor = DEFAULT_BG_COLOR.CGColor;
        
//        UIImageView *bgImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_table_bg"]];
//        _tableView.backgroundView = bgImgView;
        
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, FOOTERVIEWH)];
        footerView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = footerView;
        //        _tableView.backgroundView = self.bgImageView;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 15);
//        _tableView.backgroundColor = IColor(240, 237, 237);
        _tableView.backgroundColor = MENU_BACKGROUND_COLOR;
        _tableView.scrollEnabled = NO;
        if (self.displayView) {
            [self.displayView addSubview:_tableView];
            [self.displayView bringSubviewToFront:self];
        }
    }
    return _tableView;
}

-(UIView *)displayView {
    if (!_displayView) {
        UIView * view = [[UIView alloc] init];
        _displayView = view;
    }
    return _displayView;
}

-(UIImageView *)bgImageView {
    if (!_bgImageView) {
        _bgImageView = [[UIImageView alloc] init];
    }
    return _bgImageView;
}

- (UIImage *)makeImageWithSize:(CGSize)imageSize
                         image:(UIImage *)image
{
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    CGContextRef contextRef = UIGraphicsGetCurrentContext();
    UIBezierPath *path = [self getBezierPath:imageSize];
    CGContextAddPath(contextRef, path.CGPath);
    CGContextEOClip(contextRef);
    [image drawInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
    UIImage *arrowImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return arrowImage;
}

- (UIBezierPath *)getBezierPath:(CGSize)imageSize
{
    CGFloat arrowWidth = 8;
    CGFloat arrowHeight = 15;
    CGFloat imageW = imageSize.width;
    CGFloat imageH = imageSize.height;
    
    UIBezierPath *path;
    path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, imageSize.width, imageSize.height - arrowHeight) cornerRadius:6];
    [path moveToPoint:CGPointMake(imageW / 2.0f, imageH - 6)];
    [path addLineToPoint:CGPointMake(imageW / 2.0 - arrowWidth, imageH - arrowHeight)];
    [path addLineToPoint:CGPointMake(imageW / 2.0 + arrowWidth, imageH - arrowHeight)];
    
    [path closePath];
    
    return path;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end

@implementation ICPubMenuViewTabelViewCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_top);
            make.left.equalTo(self.mas_left);
            make.bottom.equalTo(self.mas_bottom);
            make.right.equalTo(self.mas_right);
        }];
        //        self.backgroundColor = MENU_BACKGROUND_COLOR;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

-(UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:14];
        _titleLabel.textColor = ICTEXTCOLOR_T2;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLabel];
    }
    return _titleLabel;
}

@end


